package com.example.pandaso.engines.extend;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.example.pandaso.engines.BaseEngine;
import com.example.pandaso.pojo.GoogleSearchResult;
import com.example.pandaso.pojo.GoogleSearchResult.CompleteSuggestion;
import com.example.pandaso.pojo.GoogleSearchResult.Suggestion;
import com.example.pandaso.utils.HttpUtils;


public class GoogleEngine extends BaseEngine{
    List<String> suggestsList = new ArrayList<String>();
    @Override
    public List<String> getTips(String keyword) {
        String xmlResponse = HttpUtils.getEntity("http://suggestqueries.google.com/complete/search?output=toolbar&hl=zh&q="+keyword);
        // 解析XML响应
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(GoogleSearchResult.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            GoogleSearchResult googleSearchResult = (GoogleSearchResult) unmarshaller.unmarshal(new StringReader(xmlResponse));
          // 提取suggestion中的数据
          List<CompleteSuggestion> completeSuggestions = googleSearchResult.getCompleteSuggestions();
          for (CompleteSuggestion completeSuggestion : completeSuggestions) {
              Suggestion suggestion = completeSuggestion.getSuggestion();
              suggestsList.add(suggestion.getData());
          }
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return suggestsList;
    }
    
}
